//
//  SelectLocationViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2019/2/14.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit
import MAMapKit
import AMapSearchKit

class SelectLocationViewController: UIViewController {

    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var mapView: MAMapView!
    
    @IBOutlet weak var preorderSelectPosLabel: UILabel!
    
    var location: CLLocationCoordinate2D?
    
    let search = AMapSearchAPI()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.config()
        mapView.delegate = self
        
        search?.delegate = self
        
        if let app = UIApplication.shared.delegate as? AppDelegate,
            let loc = app.userLocation {
            searchReGeo(coordinate: loc)
        }
        
        preorderSelectPosLabel.text = slipViewController?.config?.preorderSelectPos
    }

    func searchReGeo(coordinate: CLLocationCoordinate2D) {
        location = coordinate
        
        let request = AMapReGeocodeSearchRequest()
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(coordinate.latitude),
                                                 longitude: CGFloat(coordinate.longitude))
        request.requireExtension = true
        self.search?.aMapReGoecodeSearch(request)
    }
}

extension SelectLocationViewController: MAMapViewDelegate {
    
    func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
        if wasUserAction {
            searchReGeo(coordinate: mapView.centerCoordinate)
        }
    }
    
}

extension SelectLocationViewController: AMapSearchDelegate {
    
    func onReGeocodeSearchDone(_ request: AMapReGeocodeSearchRequest!, response: AMapReGeocodeSearchResponse!) {
        if response.regeocode == nil {
            return
        }
        
        if let address = response.regeocode.formattedAddress {
            addressLabel.text = address
        }
    }
    
}
